import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.util.concurrent.TimeUnit;

/**
 * @author 帅小伙
 * @date 2022/1/3
 * @description   channel预取值
 */
public class Consumer3 {

    private static final String QUEUE_NAME = "hello";
    public void consume( int ... params) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        //设置预取值    通道上最大未确认消息的数量
        int prefetchCount = 1;
        channel.basicQos(prefetchCount);
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);
        System.out.println(Thread.currentThread().getName()+"  消费者启动等待消费.........");

        String name = Thread.currentThread().getName();
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody());

            // 类似快递编号
            System.out.println(delivery.getEnvelope().getDeliveryTag());
            //根据传入时间会休息一会
            System.out.println(name+"休眠时间: "+params[0]*10);
            try {
                TimeUnit.SECONDS.sleep(params[0]*10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
            System.out.println(name+"接收到的消息"+message);

        };

        // 手动签收
        channel.basicConsume(QUEUE_NAME, false, deliverCallback, (consumerTag)->{
            System.out.println(consumerTag+"消费者取消消费信息");
        });
        //
    }
}
